<?php
class Article extends Admin_Controller{

	protected $path_upload_article;
	protected $path_upload_content;

	public function __construct(){
		parent::__construct();
		$this->load->Model(array("Marticle","Mcatalogue","Msection"));
		$this->path_upload_article = 'assets/filemanager/article/';
		$this->path_upload_content = $this->path_upload_article.'content/';
		$this->breadcrumbs->push('Article', 'admincp/article/view');
	}
	public function view(){
		if($this->input->is_ajax_request()){
            $output = $this->Marticle->listArticle();
            $this->output->set_output($output);
        }else{
	        $data['icon_page']=$this->config->item('icon_view');;
	        $data['title']='Article Manager';
	        $data['sub_title']='Article Manager';
			$this->parser->parse("article/view.tpl", NULL, $data);
		}
	}
	public function add(){
		$data['icon_page']=$this->config->item('icon_create');
        $data['title']='Create New Article';
        $data['sub_title']='Create New Article';
		$data['section']=$this->Msection->list_all();
		$dataLang = $this->registry->get('language');
    	$data['language'] = $dataLang;
		if($this->input->server('REQUEST_METHOD') == "POST"){
			$allowed_ext = array('jpg','jpeg','png','gif');
			$dataInsertImage = array();
			if(array_key_exists('image',$_FILES) && $_FILES['image']['error'] == 0 ){
            
	            $pic = $_FILES['image'];
	
	            if(!in_array(get_extension($pic['name']),$allowed_ext)){
	                exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
	            }            
	            
	            // Move the uploaded file from the temporary 
	            // directory to the uploads folder:

	            if(move_uploaded_file($pic['tmp_name'], './'.$this->path_upload_article.$pic['name'])){
	                generateThumbnail('./'.$this->path_upload_article.$pic['name'],'./'.$this->path_upload_article.'thump/'.$pic['name'],150, 150 ,0.80);
	
	                $this->load->library('image_lib');
	
	                $config['image_library'] = 'gd2';
	                $config['source_image'] = './'.$this->path_upload_article.$pic['name'];
	                $config['create_thumb'] = FALSE;
	                $config['maintain_ratio'] = TRUE;
	                $config['width']     = $this->config->item('width_article_thump');
	                $config['height']   = $this->config->item('height_article_thump');
	
	                $this->image_lib->clear();
	                $this->image_lib->initialize($config);
	                $this->image_lib->resize();

					$dataInsertImage = array(
						'image' => $this->path_upload_article.$pic['name'],
						'thumb' => $this->path_upload_article.'thump/'.$pic['name']
					);
	            }
	            
	        }

			$data_insert = array(
				'author' => $this->session->userdata('username'),
				'cata_id' => $this->input->post('catalogue'),
				'sec_id' => $this->input->post('section'),
				'created_at' => time() 
			);

			$dataInsertFinal = array_merge($data_insert, $dataInsertImage);

			$this->Marticle->insert($dataInsertFinal);
			$id = $this->db->insert_id();

			$dataInsertMain = array();
			foreach($dataLang as $lang){
				$art_title = $this->input->post('art_title_'.$lang['lang_code']);
				$art_title_url = url_title(convert_accented_characters($art_title), '-', TRUE);
				$art_content = $this->edit_article($this->input->post('art_content_'.$lang['lang_code']),$art_title_url,$lang['lang_code']);
				$dataInsertMain[] = array(
					'art_id' => $id,
					'lang_id' => $lang['id'],
					'title' => $art_title,
					'url' => url_title($art_title_url, '-', TRUE),
					'info' => $this->input->post('art_info_'.$lang['lang_code']),
					'content' => $art_content,	
				);
			}

			$this->db->insert_batch('tpt_article_content',$dataInsertMain);
			
			$this->session->set_flashdata(array("success"=>trans('message_create_successfully')));
			redirect(admincp_url()."article/view");
		}
		$this->breadcrumbs->push('Article', 'admincp/article/add');
		$this->parser->parse("article/add.tpl", NULL, $data);
	}
	
	public function edit(){
		$cache_id = $id = $this->uri->segment(4);
		$data['icon_page']=$this->config->item('icon_edit');
        $data['title']='Edit Article';
        $data['sub_title']='Edit Article';
		$data['section']=$this->Msection->list_all();
		$data['info']=$this->Marticle->get_data($id);
		$dataLang = $this->registry->get('language');
		$data['language'] = $dataLang;
		if($this->input->server('REQUEST_METHOD') == "POST"){
			$allowed_ext = array('jpg','jpeg','png','gif');
			$dataUpdateImage = array();
			if(array_key_exists('image',$_FILES) && $_FILES['image']['error'] == 0 ){
            
	            $pic = $_FILES['image'];
	
	            if(!in_array(get_extension($pic['name']),$allowed_ext)){
	                exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
	            }
	            
	            // Move the uploaded file from the temporary 
	            // directory to the uploads folder:

	            if(move_uploaded_file($pic['tmp_name'], './'.$this->path_upload_article.$pic['name'])){
	                generateThumbnail('./'.$this->path_upload_article.$pic['name'],'./'.$this->path_upload_article.'thump/'.$pic['name'],150, 150 ,0.80);
	
	                $this->load->library('image_lib');
	
	                $config['image_library'] = 'gd2';
	                $config['source_image'] = './'.$this->path_upload_article.$pic['name'];
	                $config['create_thumb'] = FALSE;
	                $config['maintain_ratio'] = TRUE;
	                $config['width']     = $this->config->item('width_article_thump');
	                $config['height']   = $this->config->item('height_article_thump');
	
	                $this->image_lib->clear();
	                $this->image_lib->initialize($config);
	                $this->image_lib->resize();

					$dataUpdateImage = array(
						'image' => $this->path_upload_article.$pic['name'],
						'thumb' => $this->path_upload_article.'thump/'.$pic['name']
					);
	            }
	            
	        }
			$dataUpdate = array(
				'cata_id' => $this->input->post('catalogue'),
				'sec_id' => $this->input->post('section'),
				'updated_at' => time() 
			);

			$dataUpdateFinal = array_merge($dataUpdate,$dataUpdateImage);
			$this->db->where('id',$id);
			$this->db->update('tpt_article', $dataUpdateFinal);

			$dataUpdateMain = array();
			foreach($dataLang as $lang){
				$art_title = $this->input->post('art_title_'.$lang['lang_code']);
				$art_title_url = url_title(convert_accented_characters($art_title), '-', TRUE);
				$art_content = $this->edit_article($this->input->post('art_content_'.$lang['lang_code']),$art_title_url,$lang['lang_code']);
				$dataUpdateMain = array(
					'title' => $art_title,
					'url' => $art_title_url,
					'info' => $this->input->post('art_info_'.$lang['lang_code']),
					'content' => $art_content,
				);
				$this->db->where('art_id',$id);
				$this->db->where('lang_id',$lang['id']);
				$this->db->update('tpt_article_content', $dataUpdateMain); 	
			}
			
			$this->session->set_flashdata(array("success"=>trans('message_edit_successfully')));
			redirect(admincp_url()."article/view");	
		}
		$this->breadcrumbs->push('Article', 'admincp/article/edit/'.$id);
		$this->parser->parse("article/edit.tpl", $cache_id, $data);
	}
	
	public function delete(){
		$id = $this->uri->segment(4);
		$this->Marticle->delete($id);
		$this->session->set_flashdata(array("success"=>trans('message_delete_successfully')));
		redirect(admincp_url()."article/view");	
	}

	public function process(){
		if($this->input->is_ajax_request()){
			$id = $this->input->post("sec_id");
			$data = $this->Mcatalogue->list_all_by_sec_id($id);
			echo json_encode($data);
		}
	}

	public function check(){
		if($this->input->is_ajax_request()){
			$id = $this->input->post("id");
			$status = $this->input->post("status");
			$active = $this->input->post("active");
			$deactive = $this->input->post("deactive");
			if($status == $active){
				$html = $deactive;
				$check = '0';				
			}
			if($status == $deactive){
				$html = $active;
				$check = '1';
			}
			$data['check'] = $check;
			$this->Marticle->update($data, $id);
			echo $html;
		}
	}

	public function edit_article($str,$title_url,$lang){
		header('Content-Type: text/html; charset=utf-8');
		preg_match_all('/<img[^>]+>/i',$str, $images); 
		if(!empty($images[0])){
			$image = array();
			$i=1;
			foreach($images[0] as $key => $img){
				preg_match_all('/(src)=("[^"]*")/i',$img, $item);
				if(!empty($item[2][0])){
					$oldNameSource = $item[2][0];
					if (strpos($oldNameSource, '../../../../') !== false) { 
					    $oldName = str_replace('../../../../', '', $oldNameSource);
						$oldName = str_replace('"', '', $oldName);
						$pathOldName = APPPATH."../".$oldName;
						$ext = strtolower(array_pop(explode('.',$pathOldName)));
						$pathNewName = $this->path_upload_content.$lang.'-'.$title_url.'-'.$i.'.'.$ext;
						rename($pathOldName, $pathNewName);
						$str = str_replace($oldNameSource, base_url().$pathNewName, $str);
					}
				}
				$i++;
			}
		}
		return $str;
	}


}